package com.jiangyg.mall.core.support.async;

import com.jiangyg.mall.core.utils.Logger;
import com.jiangyg.mall.core.utils.springframework.ApplicationContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;

import java.lang.reflect.Method;

/**
 * 类描述：异步自定义异常处理类
 *
 * @author jiangyg
 * @version 2.0
 * @date 2020-10-18
 */
@Slf4j
public class AsyncUncaughtExceptionHandlerImpl implements AsyncUncaughtExceptionHandler {

    @Override
    public void handleUncaughtException(Throwable ex, Method method, Object... params) {
        // 获取指定的自定义异常处理类
        ExceptionHandler annotation = method.getAnnotation(ExceptionHandler.class);
        // 如果没有指定自定义异常处理则输出日志
        if (annotation == null) {
            Logger.error(log, () -> String.format("执行异步方法报错。方法: %s, 参数: %s", method.getName(), params), ex);
            return;
        }
        // 如果指定自定义异常处理则执行
        Class<? extends AsyncUncaughtExceptionHandler> clazz = annotation.value();
        AsyncUncaughtExceptionHandler handler = ApplicationContextUtils.getBean(clazz);
        // 如果bean容器找不到则新建对象
        if (handler == null) {
            try {
                handler = clazz.newInstance();
            } catch (Exception e) {
                Logger.error(log, () -> String.format("初始化对象%s出错", clazz), e);
            }
        }
        handler.handleUncaughtException(ex, method, params);
    }

}
